package com.east.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import com.east.dto.UserDTO;
import com.east.entity.User;
import com.east.mapper.UserMapper;
import com.east.query.BaseQuery;
import com.east.result.Result;
import com.east.service.UserService;
import com.east.utils.CodeEnum;
import com.east.utils.Constants;
import com.east.utils.PageData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByLoginAct(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        return user;
    }

    @Override
    public Result pageSearchUser(String phone, String loginAct, String name, Integer currentPage, Integer pageSize) {
        Page<User> page = PageHelper.startPage(currentPage, pageSize);
        userMapper.searchUser(phone, loginAct, name);
        // 脱敏，用户密码不能传到前端
        page.getResult().stream().forEach(user -> {
            user.setLoginPwd("");

        });
        PageData<User> userPageData = new PageData<>(currentPage, pageSize,
                Integer.valueOf(page.getTotal() + ""), page.getPages(), page.getResult());
        return Result.OK(userPageData);
    }

    @Override
    public Result deleteUserByIds(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return Result.FAIL("请选择用户");
        }
        int i = userMapper.deleteUserByIds(ids);
        return i > 1 ? Result.OK(CodeEnum.DELETE_OK) : Result.FAIL("删除失败");
    }

    @Override
    public Result userDetail(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (Objects.isNull(user)) {
            return Result.FAIL("该用户不存在");
        }
        user.setLoginPwd("");
        return Result.OK(user);
    }

    @Override
    public Result addUser(UserDTO userDTO) {
        User loginUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = BeanUtil.copyProperties(userDTO, User.class);
        user.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        user.setCreateBy(loginUser.getId());
        user.setLoginPwd(bCryptPasswordEncoder.encode(user.getLoginPwd()));
        int insert = userMapper.addUser(user);
        return insert > 0 ? Result.OK(CodeEnum.ADD_USER_OK) : Result.FAIL("增加用户失败");
    }

    @Override
    public Result updateUser(UserDTO userDTO) {
        User loginUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = BeanUtil.copyProperties(userDTO, User.class);
        user.setEditTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        user.setEditBy(loginUser.getId());
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i > 0 ? Result.OK() : Result.FAIL();
    }

    @Override
    public Result deleteUser(Integer id) {
        int i = userMapper.deleteByPrimaryKey(id.longValue());
        return i > 0 ? Result.OK() : Result.FAIL("删除失败");
    }

    @Override
    public Result getAllUserNames() {
        // 1. 先去 redis中查找
        // 2. redis中不存在，去数据库查找
        BaseQuery baseQuery = new BaseQuery();
        List<Map<Integer, String>> allUserNames = userMapper.getAllUserNames(baseQuery);
        return Result.OK(allUserNames);
    }

    @Override
    public User info(Long id) {
        return userMapper.info(id);
    }
}
